<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Card,
  Checkbox,
  Col,
  DatePicker,
  Form,
  FormItem,
  Input,
  message,
  Modal,
  Radio,
  Row,
  Select,
  SelectOption,
  Table,
  Tag,
  Textarea,
  Timeline,
  TimelineItem,
} from 'ant-design-vue';

import StatisticsCard from '#/components/hotel/StatisticsCard.vue';

const router = useRouter();

// 状态管理
const showAddWorkOrderModal = ref(false);
const showAddTechnicianModal = ref(false);
const showQualityInspectionModal = ref(false);

// 表单引用
const workOrderFormRef = ref();
const technicianFormRef = ref();
const inspectionFormRef = ref();

// 统计数据
const statistics = reactive({
  totalWorkOrders: 156,
  workOrderChange: 12,
  pendingWorkOrders: 23,
  pendingChange: -5,
  processingWorkOrders: 8,
  processingChange: 3,
  completedWorkOrders: 125,
  completedChange: 8,
});

// 表单数据
const workOrderForm = reactive({
  roomNumber: '',
  type: '',
  priority: 'medium',
  estimatedTime: null,
  description: '',
  contactPerson: '',
  contactPhone: '',
});

const technicianForm = reactive({
  name: '',
  specialty: [],
  phone: '',
  experience: '',
});

const inspectionForm = reactive({
  workOrderId: '',
  items: [],
  result: 'pass',
  comments: '',
});

// 表单验证规则
const workOrderRules = {
  roomNumber: [{ required: true, message: '请选择房间号' }],
  type: [{ required: true, message: '请选择报修类型' }],
  priority: [{ required: true, message: '请选择优先级' }],
  description: [{ required: true, message: '请描述问题' }],
  contactPerson: [{ required: true, message: '请输入联系人' }],
  contactPhone: [{ required: true, message: '请输入联系电话' }],
};

const technicianRules = {
  name: [{ required: true, message: '请输入姓名' }],
  specialty: [{ required: true, message: '请选择专业领域' }],
  phone: [{ required: true, message: '请输入联系电话' }],
  experience: [{ required: true, message: '请输入工作经验' }],
};

const inspectionRules = {
  workOrderId: [{ required: true, message: '请选择工单' }],
  items: [{ required: true, message: '请选择检查项目' }],
  result: [{ required: true, message: '请选择检查结果' }],
};

// 可用房间
const availableRooms = ref([
  { id: 1, roomNumber: '101' },
  { id: 2, roomNumber: '102' },
  { id: 3, roomNumber: '201' },
  { id: 4, roomNumber: '202' },
  { id: 5, roomNumber: '301' },
]);

// 今日工单数据
const todayWorkOrders = ref([
  {
    id: 1,
    workOrderNumber: 'WO-2024-001',
    roomNumber: '101',
    type: 'electrical',
    priority: 'high',
    status: 'pending',
    description: '空调不制冷',
    technician: '张师傅',
    createdAt: '2024-01-15 09:30',
  },
  {
    id: 2,
    workOrderNumber: 'WO-2024-002',
    roomNumber: '205',
    type: 'plumbing',
    priority: 'medium',
    status: 'processing',
    description: '水龙头漏水',
    technician: '李师傅',
    createdAt: '2024-01-15 10:15',
  },
  {
    id: 3,
    workOrderNumber: 'WO-2024-003',
    roomNumber: '302',
    type: 'appliance',
    priority: 'low',
    status: 'completed',
    description: '电视遥控器失灵',
    technician: '王师傅',
    createdAt: '2024-01-15 11:00',
  },
]);

// 最近活动数据
const recentActivities = ref([
  {
    id: 1,
    title: '工单WO-2024-003已完成',
    description: '王师傅完成了302房间的电视维修',
    time: '2小时前',
    color: 'green',
  },
  {
    id: 2,
    title: '新工单WO-2024-004创建',
    description: '101房间报修空调问题',
    time: '3小时前',
    color: 'blue',
  },
  {
    id: 3,
    title: '工单WO-2024-002开始处理',
    description: '李师傅开始处理205房间水管问题',
    time: '4小时前',
    color: 'orange',
  },
  {
    id: 4,
    title: '质量检查通过',
    description: 'WO-2024-001维修质量检查通过',
    time: '6小时前',
    color: 'green',
  },
]);

// 已完成工单（用于质量检查）
const completedWorkOrders = ref([
  { id: 1, workOrderNumber: 'WO-2024-001' },
  { id: 2, workOrderNumber: 'WO-2024-002' },
  { id: 3, workOrderNumber: 'WO-2024-003' },
]);

// 表格列定义
const todayWorkOrderColumns = [
  {
    title: '工单号',
    dataIndex: 'workOrderNumber',
    key: 'workOrderNumber',
  },
  {
    title: '房间号',
    dataIndex: 'roomNumber',
    key: 'roomNumber',
  },
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
  },
  {
    title: '优先级',
    dataIndex: 'priority',
    key: 'priority',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
  },
  {
    title: '维修人员',
    dataIndex: 'technician',
    key: 'technician',
  },
  {
    title: '操作',
    key: 'action',
  },
];

// 状态和优先级相关函数
const getStatusColor = (status: string) => {
  const colors: Record<string, string> = {
    pending: 'orange',
    processing: 'blue',
    completed: 'green',
    cancelled: 'red',
  };
  return colors[status] || 'default';
};

const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    pending: '待处理',
    processing: '处理中',
    completed: '已完成',
    cancelled: '已取消',
  };
  return texts[status] || status;
};

const getPriorityColor = (priority: string) => {
  const colors: Record<string, string> = {
    low: 'green',
    medium: 'blue',
    high: 'orange',
    urgent: 'red',
  };
  return colors[priority] || 'default';
};

const getPriorityText = (priority: string) => {
  const texts: Record<string, string> = {
    low: '低',
    medium: '中',
    high: '高',
    urgent: '紧急',
  };
  return texts[priority] || priority;
};

// 导航函数
const navigateToWorkOrders = () => {
  router.push('/hotel/maintenance/work-orders');
};

const navigateToTechnicians = () => {
  router.push('/hotel/maintenance/technicians');
};

const navigateToStandards = () => {
  router.push('/hotel/maintenance/standards');
};

const navigateToQuality = () => {
  router.push('/hotel/maintenance/quality');
};

const navigateToRecords = () => {
  router.push('/hotel/maintenance/records');
};

const navigateToInventory = () => {
  router.push('/hotel/maintenance/inventory');
};

// 事件处理函数
const handleAddWorkOrder = async () => {
  try {
    await workOrderFormRef.value.validate();
    message.success('维修工单创建成功');
    showAddWorkOrderModal.value = false;
    // 重置表单
    Object.assign(workOrderForm, {
      roomNumber: '',
      type: '',
      priority: 'medium',
      estimatedTime: null,
      description: '',
      contactPerson: '',
      contactPhone: '',
    });
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

const handleAddTechnician = async () => {
  try {
    await technicianFormRef.value.validate();
    message.success('维修人员添加成功');
    showAddTechnicianModal.value = false;
    // 重置表单
    Object.assign(technicianForm, {
      name: '',
      specialty: [],
      phone: '',
      experience: '',
    });
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

const handleQualityInspection = async () => {
  try {
    await inspectionFormRef.value.validate();
    message.success('质量检查提交成功');
    showQualityInspectionModal.value = false;
    // 重置表单
    Object.assign(inspectionForm, {
      workOrderId: '',
      items: [],
      result: 'pass',
      comments: '',
    });
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

const viewWorkOrderDetail = (record: any) => {
  message.info(`查看工单详情: ${record.workOrderNumber}`);
};

onMounted(() => {
  // 初始化数据
});
</script>

<template>
  <div class="maintenance-management">
    <div class="page-header">
      <h2>物业维修工单</h2>
      <Button type="primary" @click="showAddWorkOrderModal = true">
        <IconifyIcon icon="ant-design:plus-outlined" />
        新建维修工单
      </Button>
    </div>

    <!-- 统计卡片 -->
    <Row :gutter="16" class="statistics-row">
      <Col :span="6">
        <StatisticsCard
          title="总工单数"
          :value="statistics.totalWorkOrders"
          :change="statistics.workOrderChange"
          icon="ant-design:file-text-outlined"
          color="#1890ff"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="待处理"
          :value="statistics.pendingWorkOrders"
          :change="statistics.pendingChange"
          icon="ant-design:clock-circle-outlined"
          color="#faad14"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="处理中"
          :value="statistics.processingWorkOrders"
          :change="statistics.processingChange"
          icon="ant-design:tool-outlined"
          color="#52c41a"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="已完成"
          :value="statistics.completedWorkOrders"
          :change="statistics.completedChange"
          icon="ant-design:check-circle-outlined"
          color="#52c41a"
        />
      </Col>
    </Row>

    <!-- 模块卡片 -->
    <Row :gutter="16" class="module-row">
      <Col :span="8">
        <Card class="module-card" @click="navigateToWorkOrders">
          <div class="module-content">
            <div class="module-icon">
              <IconifyIcon icon="ant-design:file-text-outlined" />
            </div>
            <div class="module-info">
              <h3>工单管理</h3>
              <p>创建、分配、跟踪维修工单</p>
            </div>
          </div>
        </Card>
      </Col>
      <Col :span="8">
        <Card class="module-card" @click="navigateToTechnicians">
          <div class="module-content">
            <div class="module-icon">
              <IconifyIcon icon="ant-design:team-outlined" />
            </div>
            <div class="module-info">
              <h3>维修人员</h3>
              <p>管理维修技术人员信息</p>
            </div>
          </div>
        </Card>
      </Col>
      <Col :span="8">
        <Card class="module-card" @click="navigateToStandards">
          <div class="module-content">
            <div class="module-icon">
              <IconifyIcon icon="ant-design:setting-outlined" />
            </div>
            <div class="module-info">
              <h3>维修标准</h3>
              <p>设置维修流程和标准</p>
            </div>
          </div>
        </Card>
      </Col>
    </Row>

    <Row :gutter="16" class="module-row">
      <Col :span="8">
        <Card class="module-card" @click="navigateToQuality">
          <div class="module-content">
            <div class="module-icon">
              <IconifyIcon icon="ant-design:audit-outlined" />
            </div>
            <div class="module-info">
              <h3>质量检查</h3>
              <p>维修质量验收和评估</p>
            </div>
          </div>
        </Card>
      </Col>
      <Col :span="8">
        <Card class="module-card" @click="navigateToRecords">
          <div class="module-content">
            <div class="module-icon">
              <IconifyIcon icon="ant-design:history-outlined" />
            </div>
            <div class="module-info">
              <h3>维修记录</h3>
              <p>查看历史维修记录</p>
            </div>
          </div>
        </Card>
      </Col>
      <Col :span="8">
        <Card class="module-card" @click="navigateToInventory">
          <div class="module-content">
            <div class="module-icon">
              <IconifyIcon icon="ant-design:inbox-outlined" />
            </div>
            <div class="module-info">
              <h3>配件库存</h3>
              <p>管理维修配件和材料</p>
            </div>
          </div>
        </Card>
      </Col>
    </Row>

    <!-- 今日工单和最近活动 -->
    <Row :gutter="16" class="content-row">
      <Col :span="16">
        <Card title="今日维修工单" class="content-card">
          <Table
            :columns="todayWorkOrderColumns"
            :data-source="todayWorkOrders"
            :pagination="false"
            size="small"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'status'">
                <Tag :color="getStatusColor(record.status)">
                  {{ getStatusText(record.status) }}
                </Tag>
              </template>
              <template v-else-if="column.key === 'priority'">
                <Tag :color="getPriorityColor(record.priority)">
                  {{ getPriorityText(record.priority) }}
                </Tag>
              </template>
              <template v-else-if="column.key === 'action'">
                <Button
                  type="link"
                  size="small"
                  @click="viewWorkOrderDetail(record)"
                >
                  查看详情
                </Button>
              </template>
            </template>
          </Table>
        </Card>
      </Col>
      <Col :span="8">
        <Card title="最近维修活动" class="content-card">
          <Timeline>
            <TimelineItem
              v-for="activity in recentActivities"
              :key="activity.id"
              :color="activity.color"
            >
              <div class="activity-content">
                <div class="activity-title">{{ activity.title }}</div>
                <div class="activity-desc">{{ activity.description }}</div>
                <div class="activity-time">{{ activity.time }}</div>
              </div>
            </TimelineItem>
          </Timeline>
        </Card>
      </Col>
    </Row>

    <!-- 新建维修工单弹窗 -->
    <Modal
      v-model:open="showAddWorkOrderModal"
      title="新建维修工单"
      width="600px"
      @ok="handleAddWorkOrder"
      @cancel="showAddWorkOrderModal = false"
    >
      <Form
        ref="workOrderFormRef"
        :model="workOrderForm"
        :rules="workOrderRules"
        layout="vertical"
      >
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="房间号" name="roomNumber">
              <Select
                v-model:value="workOrderForm.roomNumber"
                placeholder="选择房间"
                show-search
              >
                <SelectOption
                  v-for="room in availableRooms"
                  :key="room.id"
                  :value="room.roomNumber"
                >
                  {{ room.roomNumber }}
                </SelectOption>
              </Select>
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="报修类型" name="type">
              <Select
                v-model:value="workOrderForm.type"
                placeholder="选择报修类型"
              >
                <SelectOption value="electrical">电气维修</SelectOption>
                <SelectOption value="plumbing">水管维修</SelectOption>
                <SelectOption value="appliance">家电维修</SelectOption>
                <SelectOption value="furniture">家具维修</SelectOption>
                <SelectOption value="structure">结构维修</SelectOption>
                <SelectOption value="other">其他</SelectOption>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="优先级" name="priority">
              <Select
                v-model:value="workOrderForm.priority"
                placeholder="选择优先级"
              >
                <SelectOption value="low">低</SelectOption>
                <SelectOption value="medium">中</SelectOption>
                <SelectOption value="high">高</SelectOption>
                <SelectOption value="urgent">紧急</SelectOption>
              </Select>
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="预计完成时间" name="estimatedTime">
              <DatePicker
                v-model:value="workOrderForm.estimatedTime"
                placeholder="选择日期"
                style="width: 100%"
              />
            </FormItem>
          </Col>
        </Row>
        <FormItem label="问题描述" name="description">
          <Textarea
            v-model:value="workOrderForm.description"
            placeholder="请详细描述问题"
            :rows="4"
          />
        </FormItem>
        <FormItem label="联系人" name="contactPerson">
          <Input
            v-model:value="workOrderForm.contactPerson"
            placeholder="联系人姓名"
          />
        </FormItem>
        <FormItem label="联系电话" name="contactPhone">
          <Input
            v-model:value="workOrderForm.contactPhone"
            placeholder="联系电话"
          />
        </FormItem>
      </Form>
    </Modal>

    <!-- 添加维修人员弹窗 -->
    <Modal
      v-model:open="showAddTechnicianModal"
      title="添加维修人员"
      width="500px"
      @ok="handleAddTechnician"
      @cancel="showAddTechnicianModal = false"
    >
      <Form
        ref="technicianFormRef"
        :model="technicianForm"
        :rules="technicianRules"
        layout="vertical"
      >
        <FormItem label="姓名" name="name">
          <Input
            v-model:value="technicianForm.name"
            placeholder="维修人员姓名"
          />
        </FormItem>
        <FormItem label="专业领域" name="specialty">
          <Select
            v-model:value="technicianForm.specialty"
            placeholder="选择专业领域"
            mode="multiple"
          >
            <SelectOption value="electrical">电气</SelectOption>
            <SelectOption value="plumbing">水管</SelectOption>
            <SelectOption value="appliance">家电</SelectOption>
            <SelectOption value="furniture">家具</SelectOption>
            <SelectOption value="structure">结构</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="联系电话" name="phone">
          <Input v-model:value="technicianForm.phone" placeholder="联系电话" />
        </FormItem>
        <FormItem label="工作经验" name="experience">
          <Input
            v-model:value="technicianForm.experience"
            placeholder="工作经验（年）"
          />
        </FormItem>
      </Form>
    </Modal>

    <!-- 质量检查弹窗 -->
    <Modal
      v-model:open="showQualityInspectionModal"
      title="维修质量检查"
      width="600px"
      @ok="handleQualityInspection"
      @cancel="showQualityInspectionModal = false"
    >
      <Form
        ref="inspectionFormRef"
        :model="inspectionForm"
        :rules="inspectionRules"
        layout="vertical"
      >
        <FormItem label="工单号" name="workOrderId">
          <Select
            v-model:value="inspectionForm.workOrderId"
            placeholder="选择工单"
          >
            <SelectOption
              v-for="workOrder in completedWorkOrders"
              :key="workOrder.id"
              :value="workOrder.id"
            >
              {{ workOrder.workOrderNumber }}
            </SelectOption>
          </Select>
        </FormItem>
        <FormItem label="检查项目" name="items">
          <Checkbox.Group v-model:value="inspectionForm.items">
            <Checkbox value="quality">维修质量</Checkbox>
            <Checkbox value="safety">安全标准</Checkbox>
            <Checkbox value="cleanliness">现场清洁</Checkbox>
            <Checkbox value="documentation">文档完整</Checkbox>
          </Checkbox.Group>
        </FormItem>
        <FormItem label="检查结果" name="result">
          <Radio.Group v-model:value="inspectionForm.result">
            <Radio value="pass">通过</Radio>
            <Radio value="fail">不通过</Radio>
          </Radio.Group>
        </FormItem>
        <FormItem label="检查意见" name="comments">
          <Textarea
            v-model:value="inspectionForm.comments"
            placeholder="检查意见"
            :rows="3"
          />
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<style scoped>
.maintenance-management {
  padding: 24px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.statistics-row {
  margin-bottom: 24px;
}

.module-row {
  margin-bottom: 16px;
}

.module-card {
  height: 120px;
  cursor: pointer;
  transition: all 0.3s;
}

.module-card:hover {
  box-shadow: 0 4px 12px rgb(0 0 0 / 10%);
  transform: translateY(-2px);
}

.module-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.module-icon {
  margin-right: 16px;
  font-size: 32px;
  color: #1890ff;
}

.module-info h3 {
  margin: 0 0 8px;
  font-size: 16px;
  font-weight: 600;
}

.module-info p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.content-row {
  margin-top: 24px;
}

.content-card {
  height: 400px;
}

.activity-content {
  padding-left: 8px;
}

.activity-title {
  margin-bottom: 4px;
  font-weight: 500;
}

.activity-desc {
  margin-bottom: 4px;
  font-size: 12px;
  color: #666;
}

.activity-time {
  font-size: 12px;
  color: #999;
}

:deep(.ant-card-body) {
  padding: 12px;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 500;
  background-color: #fafafa;
}

:deep(.ant-timeline-item-content) {
  margin-left: 16px;
}
</style>
